package com.negative.activities;

import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import com.negative.data.EventItem;
import com.negative.utils.APIHelper;

import android.app.Application;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class NegativeApplication extends Application{

	private ArrayList<EventItem> eventList;
	private Date getEventTime;
	private static final long eventRefreshTime = 1000*60*5;
	private HashMap<String, Bitmap> eventsPicHash;
	private ArrayList<String> adUrls;

	private boolean isRefreshedPictured;
	private boolean isWaiting;

	@Override
	public void onCreate() {
		eventsPicHash = new HashMap<String, Bitmap>();
		isRefreshedPictured = false;
		super.onCreate();
	}

	public ArrayList<EventItem> getEventList() {
		if(eventList == null || getEventTime == null || new Date().getTime() - getEventTime.getTime() > eventRefreshTime)
		{
			APIHelper api = new APIHelper();
			ArrayList<EventItem> events;
			try {
				events = api.getEventList();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				events = new ArrayList<EventItem>();
			}
			setEventList(events);
		}
		return eventList;
	}

	public void setEventList(ArrayList<EventItem> eventList) {
		this.eventList = eventList;
		refreshEventsPic();
		getEventTime = new Date();
	}
	
	private void refreshEventsPic() {
		isRefreshedPictured = false;
				for (EventItem event : eventList) {
					if(eventsPicHash.get(event.getPicture()) == null )
					{
						getPicOnline(event.getPicture());
					}
				}
				isRefreshedPictured = true;
	}

	private void getPicOnline(final String picture) {

		isWaiting = true;
		Thread t = new Thread(){
			@Override
			public void run() {
				URL url;
				try {
					url = new URL(getString(R.string.pic_url) + picture);
					Bitmap icon = BitmapFactory.decodeStream(url.openConnection().getInputStream());
					eventsPicHash.put(picture, icon);
				} catch (Exception e) {
					
				}
				isWaiting = false;
			}
		};
		t.start();
		while(isWaiting);
	}

	public Bitmap getEventPic(String eventPicUrl)
	{
		Bitmap icon = null;
		if(isRefreshedPictured) {
			icon = eventsPicHash.get(eventPicUrl);
		}
		if(icon == null)
		{
			getPicOnline(eventPicUrl);
			icon = eventsPicHash.get(eventPicUrl);
		}
		if(icon == null)
		{
			icon = BitmapFactory.decodeResource(getResources(), R.drawable.logo_negativ_plus_black);
		}
		return icon;
	}
	
	public void setAdUrls(ArrayList<String> urls) {
		adUrls = urls;
	}
	
	public ArrayList<String> getAdUrls() {
		return adUrls;
	}
}
